package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.dto.ShoppingCartDTO;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.entity.ShoppingCart;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

@Service
@Slf4j
public class ShoppingCartServiceImpl implements ShoppingCartService {

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetmealMapper setmealMapper;

    /**
     * 添加购物车
     * @param shoppingCartDTO
     */
    // public void addShoppingCart(ShoppingCartDTO shoppingCartDTO) {

    //     //判断当前加入到购物车中的商品是否已经存在了
    //     ShoppingCart shoppingCart = new ShoppingCart();
    //     BeanUtils.copyProperties(shoppingCartDTO,shoppingCart);
    //     Long userId = BaseContext.getCurrentId();
    //     shoppingCart.setUserId(userId);

    //     List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);

    //     //如果已经存在了，只需要将数量加一
    //     if (list != null && list.size() > 0){
    //         ShoppingCart cart = list.get(0);
    //         cart.setNumber(cart.getNumber() + 1);
    //         shoppingCartMapper.updateNumberById(cart);
    //     }else {
    //         //如果不存在，需要插入一条购物车数量
    //         //判断本次添加到购物车的是菜品还是套餐
    //         Long dishId = shoppingCartDTO.getDishId();
    //         if (dishId != null){
    //             //是菜品
    //             Dish dish = dishMapper.getById(dishId);
    //             shoppingCart.setName(dish.getName());
    //             shoppingCart.setImage(dish.getImage());
    //             shoppingCart.setAmount(dish.getPrice());

    //         }else {
    //             //是套餐
    //             Long setmealId = shoppingCartDTO.getSetmealId();

    //             Setmeal setmeal = setmealMapper.getById(setmealId);
    //             shoppingCart.setName(setmeal.getName());
    //             shoppingCart.setImage(setmeal.getImage());
    //             shoppingCart.setAmount(setmeal.getPrice());

    //         }
    //         shoppingCart.setNumber(1);
    //         shoppingCart.setCreateTime(LocalDateTime.now());
    //         shoppingCartMapper.insert(shoppingCart);
    //     }
    // }


    public void addShoppingCart(ShoppingCartDTO shoppingCartDTO) {
        try {
            log.info("开始添加购物车，参数：{}", shoppingCartDTO);

            // 判断当前加入到购物车中的商品是否已经存在了
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(shoppingCartDTO, shoppingCart);
            Long userId = BaseContext.getCurrentId();
            log.info("当前登录用户ID：{}", userId);

            // 检查用户ID是否为null
            if (userId == null) {
                log.error("用户未登录，无法添加购物车");
                throw new RuntimeException("用户未登录，请先登录");
            }

            shoppingCart.setUserId(userId);

            List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);
            log.info("查询购物车结果：{}", list);

            // 如果已经存在了，只需要将数量加一
            if (list != null && list.size() > 0) {
                ShoppingCart cart = list.get(0);
                cart.setNumber(cart.getNumber() + 1);
                log.info("更新购物车数量：{}", cart);
                shoppingCartMapper.updateNumberById(cart);
            } else {
                // 如果不存在，需要插入一条购物车数量
                // 判断本次添加到购物车的是菜品还是套餐
                Long dishId = shoppingCartDTO.getDishId();
                if (dishId != null) {
                    // 是菜品
                    log.info("添加菜品到购物车，菜品ID：{}", dishId);
                    Dish dish = dishMapper.getById(dishId);
                    if (dish == null) {
                        log.error("菜品不存在，ID：{}", dishId);
                        throw new RuntimeException("菜品不存在");
                    }
                    shoppingCart.setName(dish.getName());
                    shoppingCart.setImage(dish.getImage());
                    shoppingCart.setAmount(dish.getPrice());
                } else {
                    // 是套餐
                    Long setmealId = shoppingCartDTO.getSetmealId();
                    log.info("添加套餐到购物车，套餐ID：{}", setmealId);
                    Setmeal setmeal = setmealMapper.getById(setmealId);
                    if (setmeal == null) {
                        log.error("套餐不存在，ID：{}", setmealId);
                        throw new RuntimeException("套餐不存在");
                    }
                    shoppingCart.setName(setmeal.getName());
                    shoppingCart.setImage(setmeal.getImage());
                    shoppingCart.setAmount(setmeal.getPrice());
                }
                shoppingCart.setNumber(1);
                shoppingCart.setCreateTime(LocalDateTime.now());
                log.info("插入购物车数据：{}", shoppingCart);
                shoppingCartMapper.insert(shoppingCart);
            }
            log.info("添加购物车成功");
        } catch (Exception e) {
            log.error("添加购物车异常：", e);
            throw new RuntimeException("添加购物车失败：" + e.getMessage());
        }
    }






    /**
     * 查看购物车
     * @return
     */
//    public List<ShoppingCart> showShoppingCart() {
//
//        Long userId = BaseContext.getCurrentId();
//        ShoppingCart shoppingCart = ShoppingCart.builder()
//                .userId(userId)
//                .build();
//        List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);
//
//        return list;
//    }

    public List<ShoppingCart> showShoppingCart() {
        Long userId = BaseContext.getCurrentId();
        ShoppingCart query = new ShoppingCart();
        query.setUserId(userId); // 仅设置 user_id
        return shoppingCartMapper.list(query);
    }


    /**
     * 清空购物车
     * @return
     */
    public void cleanShoppingCart() {
        Long userId = BaseContext.getCurrentId();
        shoppingCartMapper.deleteByUserId(userId);

    }

    /**
     * 删除购物车中一个商品
     * @param shoppingCartDTO
     */
    public void subShoppingCart(ShoppingCartDTO shoppingCartDTO) {
        ShoppingCart shoppingCart = new ShoppingCart();
        BeanUtils.copyProperties(shoppingCartDTO,shoppingCart);
        //设置查询条件，查询当前登录用户的购物车数据
        shoppingCart.setUserId(BaseContext.getCurrentId());

        List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);

        if(list != null && list.size() > 0){
            shoppingCart = list.get(0);

            Integer number = shoppingCart.getNumber();
            if(number == 1){
                //当前商品在购物车中的份数为1，直接删除当前记录
                shoppingCartMapper.deleteById(shoppingCart.getId());
            }else {
                //当前商品在购物车中的份数不为1，修改份数即可
                shoppingCart.setNumber(shoppingCart.getNumber() - 1);
                shoppingCartMapper.updateNumberById(shoppingCart);
            }
        }
    }


}
